package org.jeecg.modules.carinfo.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.carinfo.entity.CarRecord;
import org.jeecg.modules.carinfo.entity.CarRegister;
import org.jeecg.modules.carinfo.service.ICarRecordService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.carinfo.service.ICarRegisterService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 出入场查询
 * @Author: jeecg-boot
 * @Date: 2023-12-04
 * @Version: V1.0
 */
@Api(tags = "出入场查询")
@RestController
@RequestMapping("/carinfo/carRecord")
@Slf4j
public class CarRecordController extends JeecgController<CarRecord, ICarRecordService> {
    @Autowired
    private ICarRecordService carRecordService;
    @Autowired
    private ICarRegisterService carRegisterService;
    @Autowired
    private ISysDepartService sysDepartService;




    /**
     * 分页列表查询
     *
     * @param carRecord
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "出入场查询-分页列表查询")
    @ApiOperation(value = "出入场查询-分页列表查询", notes = "出入场查询-分页列表查询")
    @GetMapping(value = "/list/{carSort}")
    public Result<?> queryPageList(CarRecord carRecord,
                                   @PathVariable("carSort") Integer carSort,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        carRecord.setPlateNo("*"+carRecord.getPlateNo()+"*");
        QueryWrapper<CarRecord> queryWrapper = QueryGenerator.initQueryWrapper(carRecord, req.getParameterMap());
        queryWrapper.eq("car_sort", carSort);

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
        if(!username.equals("admin")){
        List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
        List<String> departNames = sysDeparts.stream()
                .filter(item -> item.getOrgType().equals("1"))
                .map(SysDepart::getDepartName)
                .collect(Collectors.toList());
        if(departNames==null||departNames.size()==0){
            return Result.error("未找到公司信息，请联系管理员");
        }
            queryWrapper.eq("company_name", departNames.get(0));
        }
        Page<CarRecord> page = new Page<CarRecord>(pageNo, pageSize);
        IPage<CarRecord> pageList = carRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询-对外
     *
     * @param carRecord
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "出入场查询-对外-分页列表查询-按类型")
    @ApiOperation(value = "出入场查询-对外-分页列表查询-按类型", notes = "出入场查询-对外-分页列表查询-按类型")
    @GetMapping(value = "/m/list/{carSort}")
    public Result<?> queryPageList2(CarRecord carRecord,
                                   @PathVariable("carSort") Integer carSort,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(name="companyName") String companyName,
                                   HttpServletRequest req) {

        carRecord.setPlateNo("*"+carRecord.getPlateNo()+"*");
        QueryWrapper<CarRecord> queryWrapper = QueryGenerator.initQueryWrapper(carRecord, req.getParameterMap());
        queryWrapper.eq("car_sort", carSort);

       /* LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
        if(!username.equals("admin")){
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if(departNames==null||departNames.size()==0){
                return Result.error("未找到公司信息，请联系管理员");
            }
            queryWrapper.eq("company_name", departNames.get(0));
        }*/
        queryWrapper.eq("company_name", companyName);
        Page<CarRecord> page = new Page<CarRecord>(pageNo, pageSize);
        IPage<CarRecord> pageList = carRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "出入场查询-分页列表查询")
    @ApiOperation(value = "出入场查询-分页列表查询", notes = "出入场查询-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CarRecord carRecord,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        carRecord.setPlateNo("*"+carRecord.getPlateNo()+"*");
        QueryWrapper<CarRecord> queryWrapper = QueryGenerator.initQueryWrapper(carRecord, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
        if(!username.equals("admin")){
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if(departNames==null||departNames.size()==0){
                return Result.error("未找到公司信息，请联系管理员");
            }
            queryWrapper.eq("company_name", departNames.get(0));
        }
        Page<CarRecord> page = new Page<CarRecord>(pageNo, pageSize);
        IPage<CarRecord> pageList = carRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "出入场查询-对外-分页列表查询")
    @ApiOperation(value = "出入场查询-对外-分页列表查询", notes = "出入场查询-对外-分页列表查询")
    @GetMapping(value = "/m/list")
    public Result<?> queryPageList2(CarRecord carRecord,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(name="companyName") String companyName,
                                   HttpServletRequest req) {
        QueryWrapper<CarRecord> queryWrapper = QueryGenerator.initQueryWrapper(carRecord, req.getParameterMap());
        queryWrapper.eq("company_name", companyName);
        queryWrapper.orderByDesc("create_time");
        Page<CarRecord> page = new Page<CarRecord>(pageNo, pageSize);
        IPage<CarRecord> pageList = carRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param carRecord
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "出入场查询-分页列表查询")
    @ApiOperation(value = "出入场查询-分页列表查询", notes = "出入场查询-分页列表查询")
    @GetMapping(value = "/listLedger")
    public Result<?> listLedger(CarRecord carRecord,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        carRecord.setPlateNo("*"+carRecord.getPlateNo()+"*");
        QueryWrapper<CarRecord> queryWrapper = QueryGenerator.initQueryWrapper(carRecord, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
        if(!username.equals("admin")){
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if(departNames==null||departNames.size()==0){
                return Result.error("未找到公司信息，请联系管理员");
            }
            queryWrapper.eq("company_name", departNames.get(0));
        }
        Page<CarRecord> page = new Page<CarRecord>(pageNo, pageSize);
        IPage<CarRecord> pageList = carRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * @param req
     * @return
     */
    @AutoLog(value = "出入场查询-统计")
    @ApiOperation(value = "出入场查询-统计", notes = "出入场查询-统计")
    @GetMapping(value = "/getCount")
    public Result<?> getCount(HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
        List<String> departNames = sysDeparts.stream()
                .filter(item -> item.getOrgType().equals("1"))
                .map(SysDepart::getDepartName)
                .collect(Collectors.toList());
        if(departNames==null||departNames.size()==0){
            return Result.error("未找到公司信息，请联系管理员");
        }

        List<Map<String, Object>> list = carRecordService.getCount(departNames.get(0));
        String[] date = new String[list.size()];
        int[] total = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            date[i] = list.get(i).get("time").toString();
            total[i] = Integer.parseInt(list.get(i).get("count").toString());
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("count", total);
        jsonObject.put("date", date);
        return Result.OK(jsonObject);
    }

    /**
     * @param req
     * @return
     */
    @AutoLog(value = "出入场查询-统计")
    @ApiOperation(value = "出入场查询-统计", notes = "出入场查询-统计")
    @GetMapping(value = "/getCountList/{flag}")
    public Result<?> getCountList(HttpServletRequest req, @PathVariable("flag") Integer flag) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
        List<String> departNames = sysDeparts.stream()
                .filter(item -> item.getOrgType().equals("1"))
                .map(SysDepart::getDepartName)
                .collect(Collectors.toList());
        if(departNames==null||departNames.size()==0){
            return Result.error("未找到公司信息，请联系管理员");
        }
        List<Map<String, Object>> list = carRecordService.getCountList(req.getParameter("start"),req.getParameter("end"),departNames.get(0),flag);
        List<Map<String, Object>> updatedList = new ArrayList<>();
        for (Map<String, Object> mapString : list) {
            Map<String, Object> updatedMap = new HashMap<>();
            String name = (String) mapString.get("name");
            if ("0".equals(name)) {
                updatedMap.put("name", "国零");
                updatedMap.put("value", mapString.get("value"));
            } else if ("1".equals(name)) {
                updatedMap.put("name", "国一");
                updatedMap.put("value", mapString.get("value"));

            } else if ("2".equals(name)) {
                updatedMap.put("name", "国二");
                updatedMap.put("value", mapString.get("value"));

            } else if ("3".equals(name)) {
                updatedMap.put("name", "国三");
                updatedMap.put("value", mapString.get("value"));

            } else if ("4".equals(name)) {
                updatedMap.put("name", "国四");
                updatedMap.put("value", mapString.get("value"));

            } else if ("5".equals(name)) {
                updatedMap.put("name", "国五");
                updatedMap.put("value", mapString.get("value"));

            } else if ("6".equals(name)) {
                updatedMap.put("name", "国六");
                updatedMap.put("value", mapString.get("value"));

            } else if ("D".equals(name)) {
                updatedMap.put("name", "新能源");
                updatedMap.put("value", mapString.get("value"));

            } else {
                updatedMap.put("name", "排放标准未知");
                updatedMap.put("value", mapString.get("value"));
            }
            updatedList.add(updatedMap);
        }
        JSONObject jsonObject = new JSONObject();
        int total=0;
        for (Map<String, Object> map : list) {
            total+=Integer.valueOf(map.get("value").toString());
        }
        jsonObject.put("count", total);
        jsonObject.put("data", updatedList);
        return Result.OK(jsonObject);
    }

    /**
     * 添加
     *
     * @param carRecord
     * @return
     */
    @AutoLog(value = "出入场查询-添加")
    @ApiOperation(value = "出入场查询-添加", notes = "出入场查询-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CarRecord carRecord) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username=loginUser.getUsername();
        if(!username.equals("admin")) {
            List<SysDepart> sysDeparts = sysDepartService.queryUserDeparts(loginUser.getId());
            List<String> departNames = sysDeparts.stream()
                    .filter(item -> item.getOrgType().equals("1"))
                    .map(SysDepart::getDepartName)
                    .collect(Collectors.toList());
            if (departNames == null || departNames.size() == 0) {
                return Result.error("未找到公司信息，请联系管理员");
            }
            carRecord.setCompanyName(departNames.get(0));
        }else {
            carRecord.setCompanyName(username);
        }
        carRecordService.save(carRecord);
        return Result.OK("添加成功！");
    }

    /**
     * 添加
     *
     * @param carRecord
     * @return
     */
    @AutoLog(value = "出入场查询-添加")
    @ApiOperation(value = "出入场查询-添加--对外", notes = "出入场查询-添加")
    @PostMapping(value = "/m/add")
    public Result<?> addM(@RequestBody CarRecord carRecord) {
        carRecord.setCompanyName("京粮（天津）粮油工业有限公司");
        if (StringUtils.isNotEmpty(carRecord.getPlateNo())) {
            //进场
            if (carRecord.getExitTime() == null) {
                LambdaQueryWrapper<CarRegister> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CarRegister::getPlateNo, carRecord.getPlateNo());
                lambdaQueryWrapper.orderByDesc(CarRegister::getUpdateTime);
                List<CarRegister> list = carRegisterService.list(lambdaQueryWrapper);
                if (list.size() > 0) {
                    // TODO 白名单字段待添加
                    getCarRegister(carRecord, list);
                    String path = convertBase64StrToImage(carRecord.getEntryPic());
                    carRecord.setEntryPic(path);
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //出厂
            } else if (carRecord.getExitTime() != null) {
                LambdaQueryWrapper<CarRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CarRecord::getPlateNo, carRecord.getPlateNo());
                lambdaQueryWrapper.isNull(CarRecord::getExitTime).orderByDesc(CarRecord::getCreateTime);
                List<CarRecord> list = carRecordService.list(lambdaQueryWrapper);
                //没有入场记录
                if (list == null || list.size() == 0) {
                    LambdaQueryWrapper<CarRegister> carRegisterLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    carRegisterLambdaQueryWrapper.eq(CarRegister::getPlateNo, carRecord.getPlateNo());
                    List<CarRegister> carRegisterList = carRegisterService.list(carRegisterLambdaQueryWrapper);
                    if (carRegisterList.size() > 0) {
                        getCarRegister(carRecord, carRegisterList);

                    }
                    String path = convertBase64StrToImage(carRecord.getExitPic());
                    carRecord.setExitPic(path);
                   carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //有入场记录
                CarRecord record = list.get(0);
                record.setExitTime(carRecord.getExitTime());
                String path = convertBase64StrToImage(carRecord.getExitPic());
                record.setExitPic(path);
                record.setBarrierGate1(carRecord.getBarrierGate1());
                carRecordService.updateById(record);
                return Result.OK("添加成功！");
            }

        }else{
            //进场
            if (carRecord.getExitTime() == null) {
                LambdaQueryWrapper<CarRegister> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CarRegister::getPin, carRecord.getPin());
                lambdaQueryWrapper.orderByDesc(CarRegister::getUpdateTime);
                List<CarRegister> list = carRegisterService.list(lambdaQueryWrapper);
                if (list.size() > 0) {
                    // TODO 白名单字段待添加
                    getCarRegister(carRecord, list);
                    String path = convertBase64StrToImage(carRecord.getEntryPic());
                    carRecord.setEntryPic(path);
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //出厂
            } else if (carRecord.getExitTime() != null) {
                LambdaQueryWrapper<CarRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CarRecord::getPin, carRecord.getPin());
                lambdaQueryWrapper.isNull(CarRecord::getExitTime).orderByDesc(CarRecord::getCreateTime);
                List<CarRecord> list = carRecordService.list(lambdaQueryWrapper);
                //没有入场记录
                if (list == null || list.size() == 0) {
                    LambdaQueryWrapper<CarRegister> carRegisterLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    carRegisterLambdaQueryWrapper.eq(CarRegister::getPlateNo, carRecord.getPlateNo());
                    List<CarRegister> carRegisterList = carRegisterService.list(carRegisterLambdaQueryWrapper);
                    if (carRegisterList.size() > 0) {
                        getCarRegister(carRecord, carRegisterList);

                    }
                    String path = convertBase64StrToImage(carRecord.getExitPic());
                    carRecord.setExitPic(path);
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //有入场记录
                CarRecord record = list.get(0);
                record.setExitTime(carRecord.getExitTime());
                String path = convertBase64StrToImage(carRecord.getExitPic());
                record.setExitPic(path);
                record.setBarrierGate1(carRecord.getBarrierGate1());
                carRecordService.updateById(record);
                return Result.OK("添加成功！");
            }

        }
        carRecordService.save(carRecord);
        return Result.OK("添加成功！");
    }

    /**
     * 添加
     *
     * @param carRecord
     * @return
     */
    @AutoLog(value = "出入场查询-移动端添加")
    @ApiOperation(value = "出入场查询-移动端添加--对外", notes = "出入场查询-移动端添加")
    @PostMapping(value = "/mt/add")
    public Result<?> addMT(@RequestBody CarRecord carRecord) {
        if (StringUtils.isNotEmpty(carRecord.getPlateNo())) {
            //进场
            if (carRecord.getExitTime() == null) {
                LambdaQueryWrapper<CarRegister> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CarRegister::getPlateNo, carRecord.getPlateNo());
                lambdaQueryWrapper.orderByDesc(CarRegister::getUpdateTime);
                List<CarRegister> list = carRegisterService.list(lambdaQueryWrapper);
                if (list.size() > 0) {
                    // TODO 白名单字段待添加
                    getCarRegister(carRecord, list);
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                if(list.size()==0){
                    carRecord.setEvnType("3");//小车
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //出厂
            } else if (carRecord.getExitTime() != null) {
                LambdaQueryWrapper<CarRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CarRecord::getPlateNo, carRecord.getPlateNo());
                lambdaQueryWrapper.isNull(CarRecord::getExitTime).orderByDesc(CarRecord::getCreateTime);
                List<CarRecord> list = carRecordService.list(lambdaQueryWrapper);
                //没有入场记录
                if (list == null || list.size() == 0) {
                    LambdaQueryWrapper<CarRegister> carRegisterLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    carRegisterLambdaQueryWrapper.eq(CarRegister::getPlateNo, carRecord.getPlateNo());
                    List<CarRegister> carRegisterList = carRegisterService.list(carRegisterLambdaQueryWrapper);
                    if (carRegisterList.size() > 0) {
                        getCarRegister(carRecord, carRegisterList);

                    }
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //有入场记录
                CarRecord record = list.get(0);
                record.setExitTime(carRecord.getExitTime());
                String path = convertBase64StrToImage(carRecord.getExitPic());
                record.setExitPic(path);
                record.setBarrierGate1(carRecord.getBarrierGate1());
                carRecordService.updateById(record);
                return Result.OK("添加成功！");
            }

        }else {
            //进场
            if (carRecord.getExitTime() == null) {
                LambdaQueryWrapper<CarRegister> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CarRegister::getPin, carRecord.getPin());
                lambdaQueryWrapper.orderByDesc(CarRegister::getUpdateTime);
                List<CarRegister> list = carRegisterService.list(lambdaQueryWrapper);
                if (list.size() > 0) {
                    // TODO 白名单字段待添加
                    getCarRegister(carRecord, list);
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                if(list.size()==0){
                    carRecord.setEvnType("3");//小车
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //出厂
            } else if (carRecord.getExitTime() != null) {
                LambdaQueryWrapper<CarRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CarRecord::getPin, carRecord.getPin());
                lambdaQueryWrapper.isNull(CarRecord::getExitTime).orderByDesc(CarRecord::getCreateTime);
                List<CarRecord> list = carRecordService.list(lambdaQueryWrapper);
                //没有入场记录
                if (list == null || list.size() == 0) {
                    LambdaQueryWrapper<CarRegister> carRegisterLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    carRegisterLambdaQueryWrapper.eq(CarRegister::getPlateNo, carRecord.getPlateNo());
                    List<CarRegister> carRegisterList = carRegisterService.list(carRegisterLambdaQueryWrapper);
                    if (carRegisterList.size() > 0) {
                        getCarRegister(carRecord, carRegisterList);

                    }
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //有入场记录
                CarRecord record = list.get(0);
                record.setExitTime(carRecord.getExitTime());
                String path = convertBase64StrToImage(carRecord.getExitPic());
                record.setExitPic(path);
                record.setBarrierGate1(carRecord.getBarrierGate1());
                carRecordService.updateById(record);
                return Result.OK("添加成功！");
            }

        }
        carRecordService.save(carRecord);
        return Result.OK("添加成功！");
    }

    @Autowired
    private ISysDictService sysDictService;

    //设置对应参数
    private void getCarRegister(@RequestBody CarRecord carRecord, List<CarRegister> carRegisterList) {
        CarRegister carRegister = carRegisterList.get(0);
        if (carRegister.getCarSort()==null){
            return;
        }
        carRecord.setCarSort(carRegister.getCarSort()); // 车辆类别
        carRecord.setEvnType(sysDictService.queryDictTextByValue("pflx", carRecord.getEvnType())); // 排放标准
        carRecord.setPlateColor(carRegister.getPlateColor()); // 车牌颜色
        carRecord.setEngineNum(carRegister.getEngineNum()); // 发动机编号
        carRecord.setInventory(carRegister.getInventory()); // 随车清单
        carRecord.setFuelType(carRegister.getFuelType()); // 燃料类型
        switch (carRegister.getCarSort()) {
            case 0:  // 进出厂车辆
                carRecord.setVin(carRegister.getVin()); // VIN
                carRecord.setLisense(carRegister.getLisense()); // 行驶证
                carRecord.setCarType(carRegister.getCarType()); // 车辆类型
                carRecord.setRegistrationTime(carRegister.getRegisterDate()); // 注册登记日期
                carRecord.setCarBrandModel(carRegister.getCarBrandModel()); // 车辆品牌型号
                carRecord.setNetworkingStatus(carRegister.getNetworkingStatus()); // 联网状态
                carRecord.setFunction(carRegister.getFunction()); // 使用性质
                //carRecord.setInTransportGoodsName(carRegister.getTransportGoodsName()); // 进厂运输货物名称
                //carRecord.setInFreightVolume(carRegister.getFreightVolume()); // 进厂运输量
                carRecord.setFleetName(carRegister.getFleet()); // 车队名称
                break;
            case 1:  // 厂内运输车辆
                carRecord.setVin(carRegister.getVin()); // VIN
                carRecord.setLisense(carRegister.getLisense()); // 行驶证
                carRecord.setRegistrationCode(carRegister.getRegistrationCode()); // 环保登记编码
                carRecord.setProducedTime(carRegister.getProducedTime()); // 生产日期
                carRecord.setRegistrationTime(carRegister.getRegisterDate()); // 注册登记日期
                carRecord.setCarBrandModel(carRegister.getCarBrandModel()); // 车辆品牌型号
                carRecord.setNetworkingStatus(carRegister.getNetworkingStatus()); // 联网状态
                carRecord.setVehicleOwner(carRegister.getVehicleOwner()); // 车辆所有人(单位)
                break;
            case 2:  // 非道路移动机械
                carRecord.setRegistrationCode(carRegister.getRegistrationCode()); // 环保登记编码
                carRecord.setProducedTime(carRegister.getProducedTime()); // 生产日期
                carRecord.setCarType(carRegister.getCarType()); // 车辆类型
                carRecord.setPin(carRegister.getPin()); // 机械环保代码/产品识别码(PIN)
                carRecord.setMechanicalModel(carRegister.getMechanicalModel()); // 机械型号
                carRecord.setEngineModel(carRegister.getEngineModel()); // 发动机型号
                carRecord.setEngineProducer(carRegister.getEngineProducer()); // 发动机生产厂
                carRecord.setEngineNum(carRegister.getEngineNum()); // 发动机编号
                carRecord.setMachineNameplate(carRegister.getMachineNameplate()); // 整车(机)铭牌
                carRecord.setEngineNameplate(carRegister.getEngineNameplate()); // 发动机铭牌
                carRecord.setVehicleOwner(carRegister.getVehicleOwner()); // 车辆所有人(单位)
                carRecord.setMachineryType(carRegister.getCarType());//机械种类
                carRecord.setMachineLabel(carRegister.getMachineLabel());//机械环保信息标签
                break;
            default:
        }
    }

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    /**
     * Base64字符串转图片
     *
     * @param base64String
     */
    public String convertBase64StrToImage(String base64String) {
        ByteArrayInputStream bais = null;
        try {
            //获取图片类型
            String suffix = "jpg";
            //获取JDK8里的解码器Base64.Decoder,将base64字符串转为字节数组
            byte[] bytes = Base64.getDecoder().decode(base64String);
            //构建字节数组输入流
            bais = new ByteArrayInputStream(bytes);
            //通过ImageIO把字节数组输入流转为BufferedImage
            BufferedImage bufferedImage = ImageIO.read(bais);
            //构建文件
            String sp = new SimpleDateFormat("yyyy_MM").format(new Date());
            sp = sp + File.separator + System.currentTimeMillis() + ".jpg";
            File imageFile = new File(uploadpath + File.separator + sp);
            if (!imageFile.exists()) {
                imageFile.mkdirs();// 创建文件根目录
            }
            //写入生成文件
            ImageIO.write(bufferedImage, suffix, imageFile);
            return sp;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bais != null) {
                    bais.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    /**
     * 编辑
     *
     * @param carRecord
     * @return
     */
    @AutoLog(value = "出入场查询-编辑")
    @ApiOperation(value = "出入场查询-编辑", notes = "出入场查询-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CarRecord carRecord) {
        carRecordService.updateById(carRecord);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出入场查询-通过id删除")
    @ApiOperation(value = "出入场查询-通过id删除", notes = "出入场查询-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        carRecordService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "出入场查询-批量删除")
    @ApiOperation(value = "出入场查询-批量删除", notes = "出入场查询-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.carRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出入场查询-通过id查询")
    @ApiOperation(value = "出入场查询-通过id查询", notes = "出入场查询-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CarRecord carRecord = carRecordService.getById(id);
        if (carRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(carRecord);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param carRecord
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CarRecord carRecord) {
        return super.exportXls(request, carRecord, CarRecord.class, "出入场查询");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CarRecord.class);
    }

    @PutMapping(value = "/syn/{id}")
    public Result<?> syn(@PathVariable String id){
        CarRecord carRecord=carRecordService.getById(id);
        String platNo=carRecord.getPlateNo();
        /*...........*/
        carRecord.setOperationalState("同步成功");
        HashMap<String,String> map=new HashMap<>();
        map.put("code","200");
        map.put("message","成功");
        map.put("data",platNo+"上传成功");
        carRecord.setOperationalResult(map.toString());
        carRecordService.updateById(carRecord);
        return Result.OK("同步成功");
    }

    @GetMapping(value = "/synBatch")
    public Result<?> synBatch(@RequestParam(name="ids",required=true) String ids) {
        List<CarRecord> carRecordList=carRecordService.listByIds(Arrays.asList(ids.split(",")));
        for(int i=0;i<carRecordList.size();i++){
            CarRecord carRecord=carRecordList.get(i);
            String platNo=carRecord.getPlateNo();
            carRecord.setOperationalState("同步成功");
            HashMap<String,String> map=new HashMap<>();
            map.put("code","200");
            map.put("message","成功");
            map.put("data",platNo+"上传成功");
            carRecord.setOperationalResult(map.toString());
            carRecordService.updateById(carRecord);
        }
        return Result.OK("批量同步成功!");
    }

    @GetMapping(value="/queryCount")
    public Result<?> queryCount(){
        Integer totalCount=carRecordService.count();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("operational_state","同步成功");
        Integer count=carRecordService.count(queryWrapper);
        BigDecimal bigDecimal=new BigDecimal(totalCount);
        BigDecimal bigDecimal1=new BigDecimal(count);

        BigDecimal rate=bigDecimal1.divide(bigDecimal, 4, RoundingMode.HALF_UP);
        BigDecimal rate1=rate.multiply(new BigDecimal(100));
        String rate2=String.valueOf(rate1).substring(0,String.valueOf(rate1).length()-2)+"%";
        Map<String,Object> map=new HashMap();
        map.put("total1",totalCount);
        map.put("total2",count);
        map.put("total3", rate2);
        return Result.OK(map);
    }

}
